using MediatR;
using B.S.BasicData.Infrature;
using B.S.BasicData.Domain;
using B.S.BasicData.EroorCode;

namespace B.S.BasicData.Api
{
    public class SlaughterInfoUpdateHandler : IRequestHandler<SlaughterInfoUpdateRequest, ApiResult<bool>>
    {
        private readonly IBaseRepository<SlaughterInfo> _repository;

        public SlaughterInfoUpdateHandler(IBaseRepository<SlaughterInfo> repository)
        {
            _repository = repository;
        }

        public async Task<ApiResult<bool>> Handle(SlaughterInfoUpdateRequest request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.Id <= 0)
                {
                    return ApiResult<bool>.Fail("无效的编号", ApiResultCode.Error);
                }

                if (string.IsNullOrWhiteSpace(request.BatchNo))
                {
                    return ApiResult<bool>.Fail("生产批次不能为空", ApiResultCode.Error);
                }

                // 获取要修改的实体
                var entity = await _repository.GetByIdAsync(request.Id);
                if (entity == null)
                {
                    return ApiResult<bool>.Fail("未找到对应的屠宰信息", ApiResultCode.NotFound);
                }

                // 更新实体属性
                entity.BatchNo = request.BatchNo;
                entity.AverageWeight = request.AverageWeight;
                entity.ArrivalTime = request.ArrivalTime;
                entity.SlaughterTime = request.SlaughterTime;

                // 保存修改
                await _repository.UpdateAsync(entity);

                return ApiResult<bool>.Success(true, "修改成功");
            }
            catch (Exception ex)
            {
                return ApiResult<bool>.Fail($"修改失败: {ex.Message}", ApiResultCode.Error);
            }
        }
    }
} 